var spawn = require('child_process').spawn;
var io = require('socket.io').listen(38412);
var fs = require('fs');

io.sockets.on('connection', function(socket) {

    var tailHandle = null;

    var startTail = function(filePath) {
        stopTail();
        console.log('[Tail] Start to tail file: ' + filePath);

        fs.exists(filePath, function(exists) {
            if (exists) {
                // start to spawn tail command
                tailHandle = spawn('tail', ['-f', filePath]);
                tailHandle.stdout.on('data', function(data) {
                    socket.emit('tailData', {lines: data.toString().split("\n")});
                });
                tailHandle.stderr.on('data', function(data) {
                    console.log('Error: ' + data.toString());
                });
            } else {
                // emit error
                console.log('[Tail] File not found: ' + filePath);
                socket.emit('tailError', 'File not found: ' + filePath);
            }
        });
    };

    var stopTail = function() {
        if (tailHandle) {
            console.log('[Tail] Stop to tail file.');
            tailHandle.kill();
        }
    };

    socket.on('switchFile', function(filePath) {
        startTail(filePath);
    });

    socket.on('disconnect', function() {
        stopTail();
    });

});